package com.qf.hytrix.service;

import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;
import com.qf.service.Book;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: Song
 * @Date: 2022-03-19 15:13
 */
public class BookCollapseCommand extends HystrixCollapser<List<Book>,Book,Integer> {

    private Integer id;

    private BookService2 bookService2;

    public BookCollapseCommand(Integer id, BookService2 bookService2) {
        super(HystrixCollapser.Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("BookCollapseCommand")).andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter().withTimerDelayInMilliseconds(200)));
        this.id = id;
        this.bookService2 = bookService2;
    }

    /**
     *  获取请求参数
     * @return
     */
    @Override
    public Integer getRequestArgument() {
        return id;
    }

    /**
     *  合并请求
     * @param collection    框架已经收集好的请求
     * @return
     */
    @Override
    protected HystrixCommand<List<Book>> createCommand(Collection<CollapsedRequest<Book, Integer>> collection) {
        //此处调用断路器
        List<Integer> ids = collection.stream().map(r -> r.getArgument()).collect(Collectors.toList());
        return new BookBatchCommand(ids,bookService2);
    }

    /**
     *  分析请求结果
     * @param books     这个是调用的结果
     * @param collection    合并起来的请求在这个集合中
     */
    @Override
    protected void mapResponseToRequests(List<Book> books, Collection<CollapsedRequest<Book, Integer>> collection) {
        int index = 0;
        for (CollapsedRequest<Book, Integer> request : collection) {
            request.setResponse(books.get(index++));
        }
    }
}
